/**
 * 自增ID插件
 * @param {*} schema 数据库schema
 * @param type {String}: 需要转换的类型。
 */

const idsModel = require("../models/system/idsModel");
const { buildErrObject } = require("../utils/buildErrObject");
function IdsPlugin(schema, type = "") {
	function formatId() {
		return async function (next, docs) {
			if (this.isNew && !this.constructor.$isArraySubdocument) {
				this.id = await buildId(type);
			}
			next();
		};
	}
	schema.pre("save", formatId()); // 新建/保存数据
}

function buildId(type) {
	return new Promise(async (resolve, reject) => {
		let ids = await idsModel.findOne({ type });
		if (ids === null) {
			let idsData = new idsModel({ type });
			idsData.save((err, docs) => {
				if (err) {
					return reject(buildErrObject(422, err.message));
				}
				resolve(docs.id);
			});
		} else {
			idsModel.findOneAndUpdate(
				{ type },
				{ $inc: { id: 1 } },
				{ new: true },
				(err, docs) => {
					if (err) return reject(buildErrObject(422, err.message));
					resolve(docs.id);
				}
			);
		}
	});
}
module.exports = IdsPlugin;
